package com.jy.controller;

import com.jy.common.Base64Image;
import com.jy.common.CSRFTokenManager;
import com.jy.common.SessionInfo;
import com.jy.common.UUIDUtils;
import com.jy.model.*;
import com.jy.service.CopeCreditService;
import com.jy.service.MoneyManageService;
import com.jy.service.UserInfoService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

/**
 *
 * 融资申请
 *
 * */
@Controller
@RequestMapping("/rzRelease")
public class MoneyManageController {
	@Resource
	private MoneyManageService mmService;
	private CopeCreditService copeCreditService;
	@Autowired
	UserInfoService userInfoService;

	@RequestMapping("/insertMoneyApply")
	public @ResponseBody
	boolean insertMoneyApply(MoneyManage mm,String dbUser,String CSRFToken,HttpSession session){

		if(CSRFToken == null || !CSRFToken.equals(session.getAttribute(CSRFTokenManager.CSRF_TOKEN_FOR_SESSION_ATTR_NAME).toString())){
			return false;
		}else {
			User user = userInfoService.getUserInfo(mm.getToken());
			if (mm != null) {
				mm.setId(UUIDUtils.getUUID());
				mm.setApply_man(user.getId());
				mm.setDids(user.getDid());
				mm.setSybcwzj(user.getUsername());
				mm.setRate(String.valueOf(Double.parseDouble(mm.getRate()) / 100));


				boolean flag = mmService.insertMoneyApply(mm, user.getId(), dbUser);
				int a = toimages(mm);
				return flag;
			} else {
				return false;
			}
		}
	}
	public Integer toimages(MoneyManage mm){
		String imgs=mm.getImgs();
		String imgnames=mm.getImgsname();
		int a=0;
		if(!"".equals(imgs)&&imgs!=null){
			imgs=mm.getImgs().substring(1);
			imgnames=mm.getImgsname().substring(1);

        String []img=imgs.split("&");
		String []imgname=imgnames.split("&");
        System.out.println("img.length:"+img.length);

		List<MoneyFile> list=new ArrayList<MoneyFile>();
        for(int i=0;i<img.length;i++){
			String b=img[i].substring(img[i].indexOf(",")+1);
			String c=imgname[i].substring(imgname[i].indexOf(",")+1);
			String filepath= Base64Image.GenerateImage(b,createPath(c));
			MoneyFile mf=new MoneyFile();
			mf.setFilename(filepath);
			mf.setMoneyId(mm.getId());
			mf.setId(UUIDUtils.getUUID());
			list.add(mf);


		}
		a=mmService.saveFilename(list);
		}
		//user.setCard_information(filepath);
		return a;
	}

	public  String createPath(String imagName){
		Properties prop =  new  Properties();
		InputStream ins =LoginController.class.getResourceAsStream("/filepath.properties");
		try {
			prop.load(ins);
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		String savePath=prop.getProperty("filepath");
		File filefolder=new File(savePath);
		if(!filefolder.isDirectory()){
			filefolder.mkdirs();
		}
		String a=imagName.substring(0, imagName.indexOf("."));
		String b=imagName.substring(imagName.indexOf("."));
		long seconds=System.currentTimeMillis();
		String path=savePath+"/"+a+"-"+seconds+b;
		return path;
	}


	/**
	 *  查询我的申请信息
	 *
	 */
	@RequestMapping("/getMoneyApplyInfo")
	public @ResponseBody List<MoneyManage> getMoneyApplyInfo(Integer state,Integer size,String token,String project_name){
		Integer[] roteId=this.getRole(token);//获得当前登陆人的所有权限
		String dids="";
		int k=0;
		for(int i=0;i<roteId.length;i++){
			if(roteId[i]==22){//融资会员
				dids=token;
				k=1;
				//break;
			}else if(roteId[i]==9){//超级管理员
				dids="";
				k=1;
				break;
			}else if(roteId[i]==25){//产品市场经理
				dids="";
				k=1;
				break;
			}else if(k!=1){
				dids="无";

			}

		}
		List<MoneyManage>list=mmService.moneyList(state,size,dids,project_name);
		return list;
	}

	/**
	 * 查询单个申请详细信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/getsingMoneyApplyInfo")
	public @ResponseBody Map<String,Object> getsingMoneyApplyInfo(String id){
		MoneyManage list=mmService.getsingMoneyApplyInfo(id);
		List<Comment> comments=mmService.getComment(list.getProcessId());
		List<MoneyFile> mfList=mmService.getImgS(id);
		Map<String,Object> map = new HashMap<String,Object>();

		map.put("mm", list);
		map.put("list", comments);
		map.put("mfList", mfList);

		return map;
	}
	/**
	 * 查询待审核信息
	 *
	 */
	@RequestMapping("/getTaskMoney")
	public @ResponseBody List<MoneyManage> getTaskMoney(Integer state,Integer size,String token) {
		Integer[] roteId=this.getRole(token);//获得当前登陆人的所有权限
		String dids="";
		for(int i=0;i<roteId.length;i++){
			if(roteId[i]==9){//超级管理员
				dids="";
				break;
			}else if(roteId[i]==25){//产品市场经理
				dids="";
				break;
			}else{
				dids=token;
				//break;
			}
		}
		List<MoneyManage> list = mmService.getTaskMoney(state,size,dids);
		return list;
	}
	@RequestMapping("/getTaskMoneyCount")
	public @ResponseBody  int getTaskMoneyCount(String token) {
		Integer[] roteId=this.getRole(token);//获得当前登陆人的所有权限
		String dids="";
		for(int i=0;i<roteId.length;i++){
			if(roteId[i]==9){//超级管理员
				dids="";
				break;
			}else if(roteId[i]==25){//产品市场经理
				dids="";
				break;
			}else{
				dids=token;
				//break;
			}
		}
		int count= mmService.getTaskMoneyCount(dids);
		return count;
	}


	/**
	 * 查询待审核单个详细信息
	 *
	 */
	@RequestMapping("/getsingTaskMoney")
	public @ResponseBody Map<String,Object> getsingTaskMoney(String id,String processId,String sjk_type) {
		System.out.println("processId:"+processId);
		MoneyManage list=null ;
		List<com.jy.model.Comment> lists=null;
		/*if(sjk_type.equals("资金管理")){
			 list = mmService.getsingTaskMoney(id);
			 lists=mmService.getCommentInfo(processId);
		}else if(sjk_type.equals("应付授信")){
			 list = copeCreditService.getsingTaskCredit(id);
			 lists=copeCreditService.getCommentInfo(processId);
		}*/
		list = mmService.getsingTaskMoney(id);
		lists=mmService.getCommentInfo(processId);
		List<MoneyFile> mfList=mmService.getImgS(id);
/*
		list.setBtns(mmService.getTaskPvm(list.getTaskid()));
*/
		Map<String,Object> map = new HashMap<String,Object>();

		map.put("mm", list);
		map.put("lists", lists);
		map.put("mfList", mfList);
/*
		map.put("list", comments);
*/
		return map;
	}
	/**
	 * 获取查询用户
	 */
	@RequestMapping("/getUsers")
	public @ResponseBody String getUsers(String name){
		List<User> list =mmService.getUsers(name);
		JSONObject jb=null;
		JSONArray jsons=new JSONArray();
		for(User d:list){
			jb=new JSONObject();
			jb.put("id", d.getId());
			jb.put("name", d.getRealname() + " -- 部门 : " + d.getDepartment_name()+"--"+d.getDepartment_name1()+"--"+d.getDepartment_name2());

		//	jb.put("name",d.getRealName()+" -- 部门 : "+d.getDepartment_name());
			jsons.add(jb);
		}
		return jsons.toString();
	}

	/**
	 * 请假申请已提交，进行审核
	 *
	 * @param pocessId
	 * @param dbUser
	 * @param
	 * @return
	 */
	@RequestMapping("/applySh")
	public @ResponseBody
	Json applySh(String pocessId,String jopen_bank,String jaccount_name,String jaccount_number, String dbUser,
				 String commons, String id,  String btnName,
				 String name, String apply_money, String dbname, String type,String token) {
		System.out.println("取到流程ID啦：" + pocessId + "代办人也来了：" + dbUser);
		User user=userInfoService.getUserInfo(token);
		Map<String, Object> variables = new HashMap<String, Object>();


		MoneyManage mm = new MoneyManage();
		if (!type.equals("1")) {// 合同编号的类型不为1时（即走六级的工作流时把各级审核人塞到记录表里）
			if (dbname != null && !dbname.equals("") && !dbname.equals("null")) {
				// 把指定的审核人插入记录
				String dbnames = dbname.substring(0, dbname.indexOf("--"));
				if (name.equals("事业部财务总监审核")) {
					mm.setSybzjl(dbnames);
				} else if (name.equals("事业部总经理审核")) {
					mm.setGyljrcpjl(dbnames);
				} else if (name.equals("供应链金融产品经理审核")) {
					mm.setGylzjl(dbnames);
				} else if (name.equals("供应链总经理审核")) {
					mm.setZc(dbnames);
				}/*
				 * else if(name.equals("总裁审核")){
				 *
				 * }
				 */
				mm.setId(id);
				if ((mm.getSybzjl() != "" && mm.getSybzjl() != null)
						|| (mm.getGyljrcpjl() != "" && mm.getGyljrcpjl() != null)
						|| (mm.getGylzjl() != "" && mm.getGylzjl() != null)
						|| (mm.getZc() != "" && mm.getZc() != null)) {
					int a = mmService.updateSHR(mm);
				}

			}

		}else{
			if (dbname != null && !dbname.equals("") && !dbname.equals("null")) {

				String dbnames = dbname.substring(0, dbname.indexOf("--"));

				if(name.equals("供应链金融经理审核")){

					mm.setSybzjjl(dbnames);
				}
			}
			mm.setId(id);

			if((mm.getSybzjjl()!="" && mm.getSybzjjl()!=null)){

				int a = mmService.updateSHR(mm);

			}
		}

		// 如果name.equals("供应链金融产品经理审核")，把甲方信息塞到记录表中
		if (name.equals("供应链金融经理审核")||name.equals("供应链金融产品经理审核")) {
			int haha = mmService.updateJiafang(jopen_bank,jaccount_name,jaccount_number,id);
		}

		variables.put("message", btnName);
		if (btnName.equals("通过") && name.equals("供应链总经理审核")) {
			if (Double.parseDouble(apply_money) > 2000000) {
				variables.put("messages", "总裁审核");
			} else {
				variables.put("messages", "其他");
			}
		}
		if (!"驳回".equals(btnName)) {
			variables.put("nextUser", dbUser);

		} else {
			mmService.updateStatus(id, 3);

		}
		int flag = mmService.updatePass(user.getId(),pocessId, variables, commons, id,
				token, btnName, dbUser);
		Json json = new Json();
		if (flag > 0) {
			json.setFlag(true);
		} else {
			json.setFlag(false);
		}

		return json;
	}

	@RequestMapping("/getGuiJi")
	public @ResponseBody List<MoneyManage> getGuiJi(Integer state,Integer size,String token) {
		Integer[] roteId=this.getRole(token);//获得当前登陆人的所有权限
		String dids="";
		int k=0;
		for(int i=0;i<roteId.length;i++){
			if(roteId[i]==22){//融资会员
				dids=token;
				k=1;
				//break;
			}else if(roteId[i]==9){//超级管理员
				dids="";
				k=1;
				break;
			}else if(roteId[i]==25){//产品市场经理
				dids="";
				k=1;
				break;
			}else if(k!=1){

				dids="无";

			}
		}
		List<MoneyManage> list = mmService.guiJiList(state,size,dids);
		return list;

	}
	@RequestMapping("/getsingGuiJi")
	public @ResponseBody MoneyManage getGuiJi(String id) {

		MoneyManage list = mmService.getsingGuiJi(id);
		return list;

	}

	@RequestMapping("/getLiuChengGuiJi")
	public @ResponseBody  List<MoneyGuiJi> getLiuChengGuiJi(Integer state,Integer size,String proId) {
		List<MoneyGuiJi> list=	mmService.getLiuChengGuiJi(state,size,proId);

		return list;

	}

public Integer [] getRole(String token){
	String custormer="finance";
	Integer[] roteId=mmService.getUserRote(token,custormer);
	return roteId;
}

	/*
         * 查看图片
         */
	@RequestMapping("/getimgurlcp")
	public void getimgurlcp(String iurl, HttpServletRequest request, HttpServletResponse response) throws IOException {
		//获取图片存放路径
		byte data[] ;
		OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
		FileInputStream is;
		//for(MoneyFile m:listOrderImg){
		String imgPath = iurl;
		imgPath.replace("/","\\\\");
		File filePic = new File(imgPath);
		if(filePic.exists()){
			//System.out.println("ddddddddddddddddd");
			is = new FileInputStream(filePic);
			int i = is.available(); // 得到文件大小
			data = new byte[i];
			is.read(data); // 读数据

			response.setContentType("image/*"); // 设置返回的文件类型

			toClient.write(data); // 输出数据

			is.close();
			toClient.close();
		}

		//}




		//request.setAttribute("iurl", listOrderImg);
		//return "moneyManage/orderImg";

	}


	@RequestMapping("/getImgS")
	public @ResponseBody  List<MoneyFile> getImgS(String iurl) {
		List<MoneyFile> listOrderImg = mmService.getImgS(iurl);

		return listOrderImg;

	}
	/**
	 * 撤销流程
	 * @param id
	 * @param process_id
	 * @return
	 */
	@RequestMapping("/iscx")
	public @ResponseBody Boolean  iscx(String id,String process_id,String realname,String userId){
		//User user=(User)session.getAttribute(SessionInfo.SessionName);
		int i=mmService.iscx(id,process_id,realname,userId);
		if(i>0){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * @param id
	 * @return 请假发起---提交申请 将状态改为1（审核中） pocessId 流程实例id id 主键id dbUser 下一执行人
	 *
	 */

	@RequestMapping("/applyTj")
	public @ResponseBody
	Boolean applySj(HttpSession session, String pocessId, String dbUser,
				 String dbname, String id, String type,String cl_time,String userId) {
		//User user = (User) session.getAttribute(SessionInfo.SessionName);
		System.out.println("取到流程ID啦：" + pocessId + "代办人也来了：" + dbUser);
		Map<String, Object> variables = new HashMap<String, Object>();
		if (type.equals("0") || type.equals("2")) {
			variables.put("message", "事业部");

			String dbnames = dbname.substring(0, dbname.indexOf("--"));
			MoneyManage mm = new MoneyManage();
			mm.setSybcwzj(dbnames);
			mm.setId(id);
			if (mm.getSybcwzj() != "" && mm.getSybcwzj() != null) {
				int a = mmService.updateSHR(mm);
			}

		} else {

			variables.put("message", "行业中心");
		}
		variables.put("nextUser", dbUser);

		boolean flag = mmService.updateState(pocessId, variables, id, dbUser,
				dbUser,cl_time,userId);

		/*Json json = new Json();
		json.setFlag(flag);*/

		return flag;
	}
	/**
	 * 添加前的查询
	 * @param session
	 * @param mm
	 * @return
	 */
	@RequestMapping("/searchApply")
	public @ResponseBody Json searchApply(HttpSession session, MoneyManage mm) {
		Json json = new Json();
		/*if(mm.getBh2s()!=null && !mm.getBh2s().equals("")){
			mm.setBh2s(mm.getBh2s()+"号资金请款单");
		}*/

		if(mm.getTypes().equals("0")){
			mm.setBh("SCF-YSZK"+mm.getBh());

		}else if(mm.getTypes().equals("1")){
			mm.setBh(mm.getBh());
		}else if(mm.getTypes().equals("2")){
			mm.setBh("SCF-XYRZ"+mm.getBh());
		}
		List<MoneyManage> list=mmService.searchApply(mm);

		if(list.size()>0){
			json.setFlag(false);
		}else{
			json.setFlag(true);
		}
		return json;
	}
}
